<?php

class CategoryModel extends Model {
    protected $_logic_table = 'category';

    public function getCategories() {
        $sql = "SELECT * FROM {$this->_table}";
        $cats = $this->_dao->getAll($sql);
        return $this->tree($cats);
    }

    /**
     * 把商品分类排序成树状的数组形式
     * @param $arr array
     * @param $pid int
     * @param $level int
     * @return array
     */
    public function tree($arr, $pid = 0, $level = 0) {
        static $tree = array();
        foreach ($arr as $cat) {
            if($cat['parent_id'] == $pid) {
                $cat['level'] = $level;
                $tree[] = $cat;
                $this->tree($arr, $cat['cat_id'], $level + 1);
            }
        }
        return $tree;
    }

    public function getSubIds($pid) {
        $sql = "SELECT * FROM {$this->_table}";
        $cats = $this->_dao->getAll($sql);
        $cats = $this->tree($cats, $pid);
        $list = array();
        foreach ($cats as $cat) {
            $list[] = $cat['cat_id'];
        }
        return $list;
    }
}